import os
from functools import wraps

from tsl_backend.fgr_api.middleware import response
from rest_framework import status
from tsl_backend.fgr_api.views.auth import AuthView as FGR_AUTH


def insert_fgr_bearer(function):
    @wraps(function)
    def fgr_authorize(request, *args, **kwargs):
        orig_username = request.data["username"]
        orig_password = request.data["password"]

        request.data._mutable = True
        request.data["username"] = os.getenv("FGR_MIDDLEWARE_USERNAME")
        request.data["password"] = os.getenv("FGR_MIDDLEWARE_PASSWORD")
        token = FGR_AUTH.getTokenFromTSL(request).data["data"]

        request.data["username"] = orig_username
        request.data["password"] = orig_password

        if token is None:
            return response(
                code=status.HTTP_401_UNAUTHORIZED,
                message="Invalid bearer token, please update env: FGR_MIDDLEWARE_USERNAME, FGR_MIDDLEWARE_PASSWORD",
            )
        res = function(request, *args, **kwargs)
        res.headers["Authorization"] = f"Bearer {token}"
        return res
    return fgr_authorize
